package com.atguigu.controller;

import com.atguigu.common.R;
import com.atguigu.entity.User;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.untils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 移动端用户管理
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private UserServiceImpl userService;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 移动端客户登录
     *
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //从请求体中获取数据
        String phone = map.get("phone").toString();//获取手机号
        String code = map.get("code").toString();//获取验证码
        // 从会话中获取验证码
        //String codeInSession = (String)session.getAttribute(phone);

        //从redis中获取验证码
        String codeInSession =(String) redisTemplate.opsForValue().get(phone);
        User user=null;
        //判断验证码是否正确
        if(codeInSession!=null&&code.equals(codeInSession)){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            user = userService.getOne(userLambdaQueryWrapper);
            //如果user为新用户，就直接注册
            if(user==null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            //如果用户登录成功，就直接删除redis中缓存的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登陆失败");
    }

    /**
     * 移动端客户发送验证码
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();//获取手机号码
        if(StringUtils.isBlank(phone)){
            return R.error("验证码发送失败");
        }
        //生成四位数的验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        //使用阿里云发送验证码
        //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
        log.info("code={}",code);
        //需要将生成的验证码保存到Session
        //session.setAttribute(phone,code);

        //需要将生成的验证码保存到redis
        redisTemplate.opsForValue().set(phone,code);
        return R.success("验证码发送成功");
    }
}
